package com.bw.service.impl;

import com.bw.domain.Role;
import com.bw.exception.MyRuntimeException;
import com.bw.mapper.RoleMapper;
import com.bw.service.RoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.util.List;

/**
 * @author bobo棒
 * @date 2025年03月13日 9:20
 */

@Service
public class RoleServiceImpl implements RoleService {
    @Autowired
    RoleMapper roleMapper;
    @Override
    public List<Role> list() {
        return roleMapper.list();
    }

    @Transactional(rollbackFor = MyRuntimeException.class)
    @Override
    public boolean add(Role role, String menuIds) {
        try {
            //如果id有值则执行添加
            if(role.getId()==null) {
                //1.保存主表--角色表--返回自增主键值
                roleMapper.add(role);
            }else{//修改角色
                roleMapper.update(role);
            }
            //保存子表--角色-权限关系表--- 中间表应该是先删除再追加
            roleMapper.deleteRoleMenu(role.getId());
             //再追加
            if(!StringUtils.isEmpty(menuIds)){

                String[] menuIdsArray = menuIds.split(",");
                for (String menuId : menuIdsArray) {
                    roleMapper.addRoleMenu(role.getId(),menuId);
                }
            }

            return true;
        }catch (Exception e){
            e.printStackTrace();
            throw new MyRuntimeException("添加角色失败");
        }

    }

    @Override
    public Role checkRoleName(String roleName) {
        return roleMapper.checkRoleName(roleName);
    }

    @Override
    public List<Integer> getMenuIdsByRoleId(Integer id) {
        return roleMapper.getMenuIdsByRoleId(id);
    }
}
